// static/user/js/modules/order.js
class OrderListManager {
    constructor() {
        this.drawer = document.getElementById('orderListDrawer');
        this.init();
    }

    async init() {
        this.bindEvents();
    }

    async loadOrders() {
        try {
            const data = await fetchData(API.ORDER.LIST);
            this.renderOrders(data);
        } catch (error) {
            Alert.show(error.message, 'error');
        }
    }

    renderOrders(orders) {
        const container = document.getElementById('orderListContent');
        container.innerHTML = orders.map(order => `
      <div class="order-item" data-order-id="${order.orderId}">
        <div class="order-item__header">
          <div class="order-id">订单号：${order.orderId}</div>
          <div class="order-status status-${order.status}">
            ${this.getStatusText(order.status)}
          </div>
        </div>
        <div class="order-item__meta">
          <p>租赁周期：${order.leaseStart} 至 ${order.leaseEnd}</p>
          <p>总金额：¥${order.totalAmount}（含押金¥${order.depositAmount}）</p>
        </div>
        <div class="order-item__actions">
          <button class="view-details-btn">查看详情</button>
        </div>
      </div>
    `).join('');
    }

    getStatusText(status) {
        const statusMap = {
            0: '待取货',
            1: '待归还',
            2: '已完成'
        };
        return statusMap[status] || '未知状态';
    }

    bindEvents() {
        // 绑定菜单点击
        document.getElementById('user-orders').addEventListener('click', () => {
            MaskLayer.show();
            this.drawer.classList.add('order-list-drawer--active');
            this.loadOrders();
        });

        // 关闭抽屉
        this.drawer.querySelector('.order-drawer-close-btn').addEventListener('click', () => {
            this.drawer.classList.remove('order-list-drawer--active');
            MaskLayer.hide();
        });

        // 查看详情
        document.getElementById('orderListContent').addEventListener('click', async (e) => {
            if (e.target.classList.contains('view-details-btn')) {
                const orderId = e.target.closest('.order-item').dataset.orderId;
                this.showOrderDetails(orderId);
            }
        });
    }

    async showOrderDetails(orderId) {
        try {
            const data = await fetchData(API.ORDER.DETAILS, { orderId: orderId });
            this.renderOrderDetailsModal(data);
        } catch (error) {
            Alert.show(error.message, 'error');
        }
    }

    renderOrderDetailsModal(data) {
        const modal = document.getElementById('orderDetailsModal');
        const mask = document.getElementById('globalMaskLayer');

        // 填充订单头信息
        modal.querySelector('.order-id').textContent = data.orderId;
        modal.querySelector('.total-amount').textContent = `¥${parseFloat(data.totalAmount).toFixed(2)}`;
        modal.querySelector('.deposit-amount').textContent = `¥${parseFloat(data.depositAmount).toFixed(2)}`;
        modal.querySelector('.lease-period').textContent =
            `${this.formatDate(data.leaseStart)} 至 ${this.formatDate(data.leaseEnd)}`;

        // 填充器材列表
        const itemsContainer = document.getElementById('orderItems');
        itemsContainer.innerHTML = data.orderDetails.map(item => `
            <div class="order-item-card">
                <img src="${item.imgUrl || '/static/default-image.jpg'}" 
                     alt="${item.itemName}"
                     onerror="this.src='/static/default-image.jpg'">
                <div class="item-info">
                    <h4>${item.itemName}</h4>
                    <div class="item-meta">
                        <div class="meta-item">
                            <span class="label">数量：</span>
                            <span class="value">${item.quantity}</span>
                        </div>
                        <div class="meta-item">
                            <span class="label">日租金：</span>
                            <span class="value">¥${parseFloat(item.dailyRate).toFixed(2)}</span>
                        </div>
                        <div class="meta-item">
                            <span class="label">租赁天数：</span>
                            <span class="value">${item.days}天</span>
                        </div>
                    </div>
                </div>
            </div>
        `).join('');

        // 显示弹窗
        modal.classList.add('active');
        mask.classList.add('mask-layer--active');
        this.bindModalCloseEvents(modal, mask);
    }

    // 优化日期格式化方法
    formatDate(dateString) {
        if (!dateString) return '--';
        try {
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
            });
        } catch (e) {
            console.error('日期格式错误:', dateString);
            return '--';
        }
    }

    bindModalCloseEvents(modal, mask) {
        const closeHandler = () => {
            modal.classList.remove('active');
            mask.classList.remove('mask-layer--active');
            // 清理事件监听
            mask.removeEventListener('click', closeHandler);
            modal.querySelector('.order-drawer-close-btn').removeEventListener('click', closeHandler);
        };

        // 绑定新的事件
        mask.addEventListener('click', closeHandler);
        modal.querySelector('.order-drawer-close-btn').addEventListener('click', closeHandler);
    }

    formatDate(timestamp) {
        if (!timestamp) return '--';
        const date = new Date(timestamp);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    new OrderListManager();
});